# -*- coding:utf-8 -*-
import datetime
import os,json,decimal,xlwt
from django_web.models import SJB_ZY,SJX_ZY,UPLOAD_LOG,TRANSFER_LOG
from django_web.tasks import transfer
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import render,redirect,HttpResponseRedirect
from django.http import FileResponse,HttpResponse,JsonResponse
from django.db import connection
from django.db.models import Count,Sum
# Create your views here.
#  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@login_required(login_url='/login')
def index(request):#首页
    return render(request, 'index.html')

def superuser_only(function):#超级管理员权限限制
    def _inner(request,*args,**kwargs):
        if not request.user.is_superuser:
            return render(request, '404.html')
        return function(request,*args,**kwargs)
    return _inner 

def user_login(request):#用户登陆
    if request.method == 'POST':
        input_username = request.POST['name']
        input_pwd = request.POST['pwd']
        user = authenticate(username=input_username,password=input_pwd)
        if user is not None:
            login(request,user)
            return redirect('/index')
        else:
            login_err = '用户名或密码错误'
            return  render(request,'login.html',{'login_err':login_err})
    return render(request,'login.html')

def user_logout(request):#用户登出
    logout(request)
    return HttpResponseRedirect('/login')

@superuser_only
@login_required(login_url='/login')
def add_user(request): #添加用户
    user = request.user
    if request.POST:
        username = request.POST['username']
        try:
            u_name=User.objects.get(username=username)
            if u_name is not None:
                return HttpResponse('{"status":"fail","msg":"用户名重复"}',content_type='application/json')
        except:
            pwd = request.POST['pass']
            phone = request.POST['phone']
            ssjg = request.POST['ssjg']
            ssbm = request.POST['ssbm']
            is_manage = request.POST['is_manage']
            if is_manage=='1':
                user = User.objects.create_user(username=username, password=pwd,email=phone,first_name=ssbm,last_name=ssjg,is_superuser='1')
            elif is_manage=='0':
                user = User.objects.create_user(username=username, password=pwd,email=phone,first_name=ssbm,last_name=ssjg,is_superuser='0')
            user.save()
            return HttpResponse('{"status":"success","msg":"添加成功"}',content_type='application/json')
    else:
        return render(request, "manage/add_user.html")

@login_required(login_url='/login')
def alter_user_pwd(request): #修改密码
    if request.method == 'POST':
        input_pwd = request.POST['pass']
        input_old_pwd = request.POST['old_pass']
        user = authenticate(username=request.user,password=input_old_pwd)
        if user is not None:
            user.set_password(input_pwd)
            user.save()
            return HttpResponse('{"status":"success","msg":"修改成功"}',content_type='application/json')
        else:
            return HttpResponse('{"status":"fail","msg":"旧密码错误"}',content_type='application/json')
    else:
        return render(request, "alter_pwd.html")

@superuser_only
@login_required(login_url='/login')
def user_info(request): #用户列表
    user_is_superuser = User.objects.get(username=request.user).is_superuser
    content_list = User.objects.all()
    paginator = Paginator(content_list, 15)
    page = request.GET.get('page', 1)
    loaded = paginator.page(page)
    context = {
        'ContentInfo': loaded,
    }
    return render(request, 'manage/user_info.html', context)

@superuser_only
@login_required(login_url='/login')
def del_user(request,post_id): #删除用户
    try:
        User.objects.filter(id=post_id).delete()
        return HttpResponse('{"status":"success","msg":"删除成功"}',content_type='application/json')
    except:
        return HttpResponse('{"status":"fail","msg":"删除失败"}',content_type='application/json')

@login_required(login_url='/login')
def search_sjb(request): #查询数据表页面
    return render(request, "cxsjb.html")

@login_required(login_url='/login')    
def search_sjb_data(request): #查询数据表信息
    try:
        keyword_t = request.POST['keyword_t']
        keyword_r = request.POST['keyword_r']
        page = request.POST['page']
        limit = request.POST['limit']
        if keyword_r=='sjb_bh':
            get_data = SJB_ZY.objects.filter(ssml_sjb_bh__contains=keyword_t).values('id','ssml_sjb_bh','sjb_zw_mc')
        elif keyword_r=='sjb_zw_mc':
            get_data = SJB_ZY.objects.filter(sjb_zw_mc__contains=keyword_t).values('id','ssml_sjb_bh','sjb_zw_mc')
        count=len(get_data)
        paginator = Paginator(get_data, limit)
        loaded = paginator.page(page)
        loaded = list(loaded)
        data={"code":0,"msg":"","count":count,"data":loaded}
        return JsonResponse(data,safe=False)
    except:
        page = request.POST['page']
        limit = request.POST['limit']
        get_data = SJB_ZY.objects.filter().values('id','ssml_sjb_bh','sjb_zw_mc')
        count=len(get_data)
        paginator = Paginator(get_data,limit)
        loaded = paginator.page(page)
        loaded = list(loaded)
        data={"code":0,"msg":"","count":count,"data":loaded}
        return JsonResponse(data,safe=False)

@login_required(login_url='/login')
def down_sjx_mb(request):#下载数据模板
    ssml_sjb_bh = request.POST['ssml_sjb_bh']
    pd = os.path.exists('excel_mb/'+ssml_sjb_bh+'.xlsx')
    filePath = 'excel_mb/' + ssml_sjb_bh + '.xlsx'
    if pd == False:
        dict1 = SJX_ZY.objects.filter(ssml_sjb_bh=ssml_sjb_bh)
        creat_excel(dict1,filePath)
    data={"status":"success","msg":"下载成功","filePath":filePath}
    return JsonResponse(data,safe=False)

@login_required(login_url='/login')
def sjx_mb_down(request,filename):#下载数据模板
    filePath = 'excel_mb/' + filename
    file = open(filePath, 'rb')
    response = FileResponse(file)
    down_name = 'attachment;filename='+filePath
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = down_name.encode('utf-8','ISO-8859-1')
    return response

@login_required(login_url='/login')
def upload_sjx_wj(request):#上传文件
    if request.method == 'POST':  
        sssjb_bh = request.POST['ssmb_bh']
        if len(sssjb_bh)==0:
            return JsonResponse({"code":1},safe=False)
        f = request.FILES['file']
        www=os.path.abspath('.')
        file_name = request.user.username+datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d%H%M%S')+'.xlsx'
        destination = open(os.path.join(www+"/upload_excel",file_name), 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
        upload_log = UPLOAD_LOG.objects.create(upload_user_name=request.user.username, file_name=file_name, ss_sjb_bh=sssjb_bh, is_success=True,is_transfer=False)
        upload_log.save()
        transfer.delay(file_name,sssjb_bh)
        data_sjb_zw_mc = SJB_ZY.objects.get(ssml_sjb_bh=sssjb_bh).sjb_zw_mc
        transfer_log = TRANSFER_LOG.objects.create(uplode_file_name=file_name,sjb_zw_mc=data_sjb_zw_mc, transfer_user_name=request.user.username,transfer_user_jg=request.user.last_name)
        transfer_log.save()
        return JsonResponse({"code":0},safe=False)
    else:
        return render(request, 'scsjx.html')

@login_required(login_url='/login')
def transfer_log(request):#传输日志
    return render(request, 'transfer_log.html')

@login_required(login_url='/login')
def transfer_log_data(request):#传输日志的数据
    user = request.user
    try:
        keyword_t = request.POST['keyword_t']
        keyword_r = request.POST['keyword_r']
        page = request.POST['page']
        limit = request.POST['limit']
        if user.is_superuser==1:
            if keyword_r=='transfer_user_jg':
                get_data = TRANSFER_LOG.objects.filter(transfer_user_jg__contains=keyword_t).values('id','uplode_file_name','sjb_zw_mc','transfer_user_name','transfer_user_jg','transfer_len','transfer_start_datetime','transfer_end_datetime').order_by('-transfer_end_datetime')
            elif keyword_r=='sjb_zw_mc':
                get_data = TRANSFER_LOG.objects.filter(sjb_zw_mc__contains=keyword_t).values('id','uplode_file_name','sjb_zw_mc','transfer_user_name','transfer_user_jg','transfer_len','transfer_start_datetime','transfer_end_datetime').order_by('-transfer_end_datetime')
        else:    
            if keyword_r=='transfer_user_jg':
                get_data = TRANSFER_LOG.objects.filter(transfer_user_jg__contains=keyword_t,transfer_user_jg=user.last_name).values('id','uplode_file_name','sjb_zw_mc','transfer_user_name','transfer_user_jg','transfer_len','transfer_start_datetime','transfer_end_datetime').order_by('-transfer_end_datetime')
            elif keyword_r=='sjb_zw_mc':
                get_data = TRANSFER_LOG.objects.filter(sjb_zw_mc__contains=keyword_t,transfer_user_jg=user.last_name).values('id','uplode_file_name','sjb_zw_mc','transfer_user_name','transfer_user_jg','transfer_len','transfer_start_datetime','transfer_end_datetime').order_by('-transfer_end_datetime')
        count=len(get_data)
        paginator = Paginator(get_data, limit)
        loaded = paginator.page(page)
        loaded = list(loaded)
        data={"code":0,"msg":"","count":count,"data":loaded}
        return JsonResponse(data,safe=False)
    except:
        page = request.POST['page']
        limit = request.POST['limit']
        if user.is_superuser==1:
            get_data = TRANSFER_LOG.objects.filter().values('id','sjb_zw_mc','uplode_file_name','transfer_user_name','transfer_user_jg','transfer_len','transfer_start_datetime','transfer_end_datetime').order_by('-transfer_end_datetime')
        else:
            get_data = TRANSFER_LOG.objects.filter(transfer_user_jg=user.last_name).values('id','sjb_zw_mc','uplode_file_name','transfer_user_name','transfer_user_jg','transfer_len','transfer_start_datetime','transfer_end_datetime').order_by('-transfer_end_datetime')
        count=len(get_data)
        paginator = Paginator(get_data,limit)
        loaded = paginator.page(page)
        loaded = list(loaded)
        data={"code":0,"msg":"","count":count,"data":loaded}
        return JsonResponse(data,safe=False)

@login_required(login_url='/login')
def down_scwj(request):#下载上传文件
    uplode_file_name = request.POST['uplode_file_name']
    data={"status":"success","msg":"下载成功","filePath":uplode_file_name}
    return JsonResponse(data,safe=False)

@login_required(login_url='/login')
def scwj_down(request,filename):#下载上传文件
    filePath = 'upload_excel/' + filename
    file = open(filePath, 'rb')
    response = FileResponse(file)
    down_name = 'attachment;filename='+filePath
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = down_name.encode('utf-8','ISO-8859-1')
    return response

@login_required(login_url='/login')
def mb(request):#数据模板
    first_name = User.objects.get(username=request.user).first_name
    last_name = User.objects.get(username=request.user).last_name
    content_list = SJB_ZY.objects.all()
    paginator = Paginator(content_list, 15)
    page = request.GET.get('page', 1)
    loaded = paginator.page(page)
    context = {
        'ContentInfo': loaded,
        'first_name': first_name,
        'last_name': last_name,
    }
    return render(request, 'cxsjb.html', context)

def creat_excel(dict1,filename):#生成数据模板
    sjx_zw_mc = []
    for i in dict1:
        sjx_zw_mc.append(i.sjx_zw_mc)
    workbook = xlwt.Workbook(encoding = 'utf-8')
    worksheet = workbook.add_sheet('sheet1')
    cols=0
    for netted in sjx_zw_mc:
        worksheet.write(0, cols, netted)
        cols=cols+1
    workbook.save(filename)

@login_required(login_url='/login')
def sjtj(request):#数据统计
    return render(request, 'sjtj.html')

@login_required(login_url='/login')
def sjtj_data(request):#数据统计
    try:
        start_time = request.POST['start_time']
        end_time = request.POST['end_time']
        page = request.POST['page']
        limit = request.POST['limit']
        result = TRANSFER_LOG.objects.filter(transfer_end_datetime__gt=start_time,transfer_end_datetime__lt=end_time).values('transfer_user_jg').annotate(count=Count('sjb_zw_mc',distinct=True),sum=Sum('transfer_len'))
        count=len(result)
        paginator = Paginator(result,limit)
        loaded = paginator.page(page)
        loaded = list(loaded)
        data={"code":0,"msg":"","count":count,"data":loaded}
        return JsonResponse(data,safe=False)
    except:
        page = request.POST['page']
        limit = request.POST['limit']
        result = TRANSFER_LOG.objects.values('transfer_user_jg').annotate(count=Count('sjb_zw_mc',distinct=True),sum=Sum('transfer_len'))
        count=len(result)
        paginator = Paginator(result,limit)
        loaded = paginator.page(page)
        loaded = list(loaded)
        data={"code":0,"msg":"","count":count,"data":loaded}
        return JsonResponse(data,safe=False)
